package _01_动态数组;

import java.util.*;
import java.util.stream.Stream;

public class _49_字母异位词分组 {

    public static void main(String[] args) {
        _49_字母异位词分组 v = new _49_字母异位词分组();
        String[] str = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> lists = v.groupAnagrams(str);
        for (List<String> list : lists) {
            System.out.println(list);
        }
    }

    // 排序，确定key
    public List<List<String>> groupAnagrams(String[] strs) {
        // 同一个组合下的字母，他的ASCII码相同
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            List<String> list = map.getOrDefault(key, new ArrayList<>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<>(map.values());
    }

    // 计数确定key
    public List<List<String>> groupAnagrams1(String[] strs) {
        // 同一个组合下的字母，他的ASCII码相同
        Map<Integer, List<String>> map = new HashMap<>();
        for (String str : strs) {
            int[] ints = new int[26];
            for (int i = 0; i < str.length(); i++) {
                ints[str.charAt(i) - 'a']++;
            }
            int key = Arrays.hashCode(ints);
            List<String> list = map.getOrDefault(key, new ArrayList<>());
            list.add(str);
            map.put(key, list);
        }
        return new ArrayList<>(map.values());
    }


}
